package com.tanhua.app.Service;

import com.tanhua.api.CommentApi;
import com.tanhua.api.UserInfoApi;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.interceptor.UserThreadLocal;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CommentService {
    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 保存动态的评论
     * @param movementId
     * @param comment
     */
    public void saveComments(String movementId, String comment) {
        Comment newComment = new Comment();
        newComment.setLikeCount(0);
        newComment.setCreated(System.currentTimeMillis());
        newComment.setCommentType(CommentType.COMMENT.getType());
        newComment.setPublishId(new ObjectId(movementId));
        newComment.setContent(comment);
        newComment.setUserId(UserThreadLocal.getid());
        Integer save = commentApi.save(newComment);

    }

    /**
     * 根据动态id查询动态下面的评论
     *
     * @param movementId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult<CommentVo> findComments(String movementId, int page, int pageSize) {
        //根据动态id，互动类型确定评论列表
        List<Comment> commentList = commentApi.findComments(movementId, page, pageSize, CommentType.COMMENT.getType());
        if (commentList==null||commentList.size() == 0 ){
            return new PageResult<>(page,pageSize,0,null);
        }
        //根据评论的userID获取到userinfo的详细信息
        List<Long> userIds = commentList.stream().map(Comment::getUserId).collect(Collectors.toList());
        //
        List<UserInfo> infoList = userInfoApi.findUserinfoByIds(userIds);

        Map<Long, UserInfo> map = infoList.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));

        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : commentList) {



            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }

        }
        return new PageResult<CommentVo>(page,pageSize,0,vos);
    }

    /**
     * 保存动态的点赞并返回点赞数
     *
     * @param movementId
     * @return
     */

    public Integer likeComment(String movementId) {
      Boolean B= commentApi.haslikeComment(movementId,UserThreadLocal.getid(),CommentType.LIKE.getType());
      if (B){
          throw new BusinessException(ErrorResult.likeError());
      }
//3、调用API保存数据到Mongodb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserThreadLocal.getid());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY +UserThreadLocal.getid();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    /**
     * 取消动态的点赞
     * @return
     */
    public Integer disLike(String movementId) {
        //1,判断是否点赞
        Boolean aBoolean = commentApi.haslikeComment(movementId, UserThreadLocal.getid(), CommentType.LIKE.getType());
        if (!aBoolean) {
     throw  new BusinessException(ErrorResult.disLikeError());
        }
       Integer likeCount= commentApi.delete(movementId,UserThreadLocal.getid(),CommentType.LIKE.getType());
        //4、拼接redis的key，删除redis里面的点赞数据
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY +UserThreadLocal.getid();
   redisTemplate.opsForHash().delete(key,hashKey);
        return likeCount;
    }

    /**
     * 动态喜欢
     * @return
     */
    public Integer love(String movementId) {
        //判断是否喜欢
        Boolean aBoolean = commentApi.haslikeComment(movementId, UserThreadLocal.getid(), CommentType.LOVE.getType());
        if (aBoolean){
            throw new BusinessException(ErrorResult.loveError());
        }
        //添加到互动
        //3、调用API保存数据到Mongodb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserThreadLocal.getid());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //4、拼接redis的key，将用户的喜欢状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY +UserThreadLocal.getid();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    /**
     * 取消动态喜欢
     * @param movementId
     * @return
     */
    public Integer unlove(String movementId) {
        //1,判断是否喜欢
        Boolean aBoolean = commentApi.haslikeComment(movementId, UserThreadLocal.getid(), CommentType.LOVE.getType());
        if (!aBoolean) {
            throw  new BusinessException(ErrorResult.disloveError());
        }
        Integer likeCount= commentApi.delete(movementId,UserThreadLocal.getid(),CommentType.LOVE.getType());
        //4、拼接redis的key，删除redis里面的喜欢数据
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY +UserThreadLocal.getid();
        redisTemplate.opsForHash().delete(key,hashKey);
        return likeCount;
    }
}

